package com.heer.gymnasium.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.api.constants.StaticValue;
import com.heer.gymnasium.R;
import com.heer.gymnasium.adapter.RechargeOfferAdapter;
import com.heer.gymnasium.constant.Extras;
import com.heer.gymnasium.widget.MyListView;
import com.heer.model.CreateRechargeBean;
import com.heer.model.SiteOfferBean;
import com.heer.model.WxPayBean;
import com.heer.gymnasium.util.PayUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by heer on 17/4/23.
 */

public class RechargeOfferActivity extends BaseActivity {
    @BindView(R.id.radio_1)
    RadioButton radio1;
    @BindView(R.id.radio_2)
    RadioButton radio2;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.list)
    MyListView list;
    @BindView(R.id.edit_other)
    EditText editOther;
    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private RechargeOfferAdapter mAdapter;
    private PayUtils payUtils;

    public static void toRechareOffer(Context context, String sid) {
        Intent intent = new Intent();
        intent.setClass(context, RechargeOfferActivity.class);
        intent.putExtra(Extras.EXTRA_ID, sid);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_recharge);
        payUtils = new PayUtils(this);
    }

    @Override
    protected void initView() {
        super.initView();
        titleBuilder.setTitleText("充值");
        list.setAdapter(mAdapter = new RechargeOfferAdapter(mContext));
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mAdapter.setTemp(position);
                editOther.setText("");
            }
        });
        editOther.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    mAdapter.setTemp(-1);
                } else {
                    if (mAdapter.getCount() != 0 && mAdapter.getTemp() == -1) {
                        mAdapter.setTemp(0);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void loadData() {
        super.loadData();
        mAppHelper.apiService().getSiteOfferList(getIntent().getStringExtra(Extras.EXTRA_ID)).enqueue(new BaseCallback<ApiResponse<List<SiteOfferBean>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<SiteOfferBean>>> call, Response<ApiResponse<List<SiteOfferBean>>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful() && response.body().isSccessful()) {
                    List<SiteOfferBean> list = response.body().getData();
                    if (null != list && list.size() > 0) {
                        mAdapter.setItems(list);
                    }
                }
                if (response.body().isTokenExpire()) {
                    toLogin();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<SiteOfferBean>>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }

    @OnClick(R.id.btn_submit)
    public void onClick(final View v) {
        final String payWay;
        StaticValue.PayType=1;

        String money = "0.01";
        if (TextUtils.isEmpty(editOther.getText().toString().trim())) {
            if (mAdapter.getTemp() == -1) {
                Toast.makeText(mContext, "请输入充值金额", Toast.LENGTH_SHORT).show();
                return;
            } else {
                money = mAdapter.getItem(mAdapter.getTemp()).getMoney();
                String regx = "[1-9]\\d*(\\.\\d+)?";
                Pattern p = Pattern.compile(regx);
                Matcher m = p.matcher(money);
                if (!m.find()) {
                    Toast.makeText(mContext, "请输入充值金额", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        } else {
            money = editOther.getText().toString();
        }

        switch (radioGroup.getCheckedRadioButtonId()) {
            case R.id.radio_1:
                payWay = "ali";
                break;
            case R.id.radio_2:
                payWay = "wx";
                break;
            default:
                payWay = "ali";
                break;
        }
        Toast.makeText(mContext, "提交", Toast.LENGTH_SHORT).show();
        final String finalMoney = money;
        mAppHelper.apiService().createRechargeOrder(getIntent().getStringExtra(Extras.EXTRA_ID), money, payWay).enqueue(new BaseCallback<ApiResponse<CreateRechargeBean>>() {
            @Override
            public void onResponse(Call<ApiResponse<CreateRechargeBean>> call, Response<ApiResponse<CreateRechargeBean>> response) {
                super.onResponse(call, response);
                if (payWay.equals("ali")) {
                    payUtils.pay(v, finalMoney, response.body().getData().getOrder_sn());
                } else {
                    mAppHelper.apiService().getWxData(response.body().getData().getOrder_sn()).enqueue(new BaseCallback<ApiResponse<WxPayBean>>() {
                        @Override
                        public void onResponse(Call<ApiResponse<WxPayBean>> call, Response<ApiResponse<WxPayBean>> response) {
                            super.onResponse(call, response);
                            if (response.isSuccessful() && response.body().isSccessful()) {
                                WxPayBean data = response.body().getData();
                                Gson gson = new Gson();
                                String json = gson.toJson(data);
                                payUtils.payWx(json);
                            } else {
                                Log.e("PAY_GET", "返回错误" + response.message());
                            }
                        }

                        @Override
                        public void onFailure(Call<ApiResponse<WxPayBean>> call, Throwable t) {
                            super.onFailure(call, t);
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<CreateRechargeBean>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }
}
